package com.learning.cloud2020.controller;

import com.learning.cloud2020.entities.Payment;
import com.learning.cloud2020.model.CommonResult;
import com.learning.cloud2020.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Value("${server.port}")
    private String serverPort;

    private final PaymentService paymentService;
    private final DiscoveryClient discoveryClient;

    public PaymentController(PaymentService paymentService, DiscoveryClient discoveryClient) {
        this.paymentService = paymentService;
        this.discoveryClient = discoveryClient;
    }


    @PostMapping("/create")
    public CommonResult create(@RequestBody Payment payment) {
        Long result = paymentService.create(payment);
        Long paymentId = payment.getId();
        if (result > 0) {
            return new CommonResult(200, "插入数据库成功主键为:"+paymentId+",serverPort：" + serverPort, result);
        } else {
            return new CommonResult(405, "插入数据库失败,serverPort：" + serverPort, result);
        }
    }

    @GetMapping("/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        return new CommonResult(200, "查询数据库成功,serverPort：" + serverPort, payment);
    }

    @GetMapping("/timeout/{sleepMillis}")
    public CommonResult<Payment> getPaymentByIdTimeOut(@PathVariable("sleepMillis") Long sleepMillis) throws InterruptedException {
        Thread.sleep(sleepMillis);
        log.info("睡眠了{}秒后我被执行了。。。。", sleepMillis);
        return new CommonResult(200, "查询数据库成功,serverPort：" + serverPort, null);
    }

    @GetMapping("/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("****element:" + service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }

        return this.discoveryClient;
    }


}
